package com.nblog.utils;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.binary.Base64;
import com.jfinal.kit.PropKit;
import com.nblog.constant.Constant;
import com.nblog.model.User;
import com.nblog.utils.encrypt.Md5Utils;

public class IWebUtils {
	/**
	 * 获取系统用户
	 * @param HttpSession
	 * @return
	 */
	public static User getCurrentSysUser(HttpSession  httpSession ) {
		User sysUser=(User)httpSession.getAttribute(Constant.FRONTUSER);
		return sysUser;
	}
	/**
	 * 保存登陆用户
	 * @param HttpSession
	 * @param user
	 */
	public static void setCurrentLoginSysUserToSession(HttpSession httpSession ,User user){
		httpSession.setAttribute(Constant.FRONTUSER,user);
	}
	public static void setCurrentLoginSysUser(HttpServletResponse response ,HttpSession httpSession,User user,Integer autoLogin){
		setCurrentLoginSysUserToSession(httpSession, user);
		if(autoLogin.equals(1)){
			//保存7天
			long expireTime=DateUtils.addDay(new Date(),7).getTime();
			Md5Utils md5=new Md5Utils();
			//得到用户名、经MD5加密后的用户密码、cookie有效时间
			String userInfo=md5.getMD5(user.getUsername()+user.getPassword()+expireTime+PropKit.get("app_key"));
			String userBase64=Base64.encodeBase64String(new String(user.getUsername()+":"+expireTime+":"+userInfo).getBytes());
			CookieUtils.addCookie(response, "token", userBase64, 60*60*24*7);
		}
	}
	
	/**
	 * 获取当前登陆的用户
	 * @param request
	 * @return
	 */
	public static User getCurrentSysUser(HttpServletRequest request){
		User sysUser=getCurrentSysUser(request.getSession());
		if(sysUser==null){
			String token=CookieUtils.getCookieByName(request, "token");
			if(CommonUtils.isNotEmpty(token)){
				String[] tokenArray=new String(Base64.decodeBase64(token)).split(":");
				if(tokenArray.length==3){
					String expireTimeStr= tokenArray[1];
					if(new Date(Long.valueOf(expireTimeStr)).after(new Date())){
						String name=tokenArray[0];
						String userInfo=tokenArray[2];
						User user=User.dao.findFirst("select * from user where username=?",name);
						if(user!=null){
							Md5Utils md5=new Md5Utils();
							String userInfo2=md5.getMD5(user.getUsername()+user.getPassword()+expireTimeStr+PropKit.get("app_key"));
							if(userInfo2.equals(userInfo)){
								sysUser=user;
								setCurrentLoginSysUserToSession(request.getSession(), sysUser);
							}
						}
					}
				}
				return sysUser;
			}
		}
		return sysUser; 
	}
	/**
	 * 清除session中的系统用户
	 * @param HttpSession
	 */
	public static void removeCurrentSysUserFromSession(HttpSession httpSession){
		httpSession.removeAttribute(Constant.FRONTUSER);
	}
	
	public static void removeCurrentSysUser(HttpServletRequest request,HttpServletResponse response){
		CookieUtils.delCookie("", request, response);
		removeCurrentSysUserFromSession(request.getSession());
	}
	
}
